#pragma once
#include <sys/types.h>
#include <sys/socket.h>
#include <list>
#include <algorithm>
#include "InetAddr.hpp"
#include "Log.hpp"
using namespace LogModule;
class UserInterface
{
public:
    virtual ~UserInterface() = default;
    virtual void SendTo(int sockfd,std::string& message) = 0;
};

class User : public UserInterface
{
public:
    User(InetAddr &id)
        :_id(id)
    {
    }
    ~User()
    {
    }
    void SendTo(int sockfd,std::string& message) override
    {
        sendto(sockfd, message.c_str(),message.size(),0,_id.Addr(),_id.In_Size());
    }
    bool operator==(InetAddr& id)
    {
        if(Sock()==id.Sock())
            return true;
        return false;
    }
    std::string Sock()
    {
        return _id.Sock();
    }
private:
    InetAddr _id;
};

class UserManager
{
public:
    UserManager()
    {

    }
    void AddUser(InetAddr& id)
    {

        for(auto& e:_list)
        {
            if(e==id)
            {        
                LOG(LogLevel::INFO)<<"用户已存在 "<<id.Sock();
                return;
            }
        }
        User user(id);
        LOG(LogLevel::INFO)<<"添加新用户 "<<id.Sock();
        _list.push_front(user);
    }
    //路由
    void Router(int sockfd,std::string& message)
    {
        for(auto& u:_list)
        {
            LOG(LogLevel::INFO)<<"message send to "<<u.Sock();
            u.SendTo(sockfd,message);
        }
    }
    void DelUser(InetAddr& id)
    {
        auto pos = remove_if(_list.begin(),_list.end(),[&id](User& user){
            return user==id;
        });
        LOG(LogLevel::INFO)<<"删除用户"<<id.Sock();
        _list.erase(pos,_list.end());
    }
    ~UserManager()
    {

    }
private:
    std::list<User> _list;
};